package com.bq.gametrade.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

public class FileUpload {

    private static final int TIME_OUT = 10*10000000;
    private static final String CHARSET = "utf-8";
    public static final String SUCCESS="1";
    public static final String FAILURE="0";

    private FileUploadListener	mListener=null;

    public static FileUpload FileUploadCreate(FileUploadListener listener)
    {
        FileUpload instance= new FileUpload();
        instance.setListener(listener);
        return instance;
    }

    public void setListener(FileUploadListener listener)
    {
        mListener=listener;
    }

    public void uploadFile(File file,String RequestURL) {

        String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
        String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false); //不允许使用缓存
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", CHARSET);
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            conn.connect();
            if(file!=null) {
                /** * 当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam=conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY); sb.append(LINE_END);
                /**
                 * 这里重点注意：
                 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */
                sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""+file.getName()+"\""+LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());

                if(mListener!=null)
                    mListener.onUploadStart();

                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];

                long size=is.available();
                int len = 0;
                int downloadLen=0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                    if(mListener!=null)
                    {
                        downloadLen+=len;
                        mListener.onUploadProgress(downloadLen, size);
                    }
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                if(res==200)
                {
                    InputStreamReader in=new InputStreamReader( conn.getInputStream());
                    BufferedReader bufReader=new BufferedReader(in);
                    String line=null;
                    StringBuffer strBuf=new StringBuffer();
                    while((line=bufReader.readLine())!=null)
                        strBuf.append(line);

                    String strRet=strBuf.toString();
                    if(mListener!=null)
                    {
                        mListener.onUploadFinished(true, strRet);
                    }

                    return;
                }
            }
        } catch (MalformedURLException e)
        { e.printStackTrace(); }
        catch (IOException e)
        { e.printStackTrace(); }

        if(mListener!=null)
        {
            mListener.onUploadFinished(false, "");
        }
    }

    public interface FileUploadListener
    {
        public void onUploadStart();
        public void onUploadProgress(long nSize,long allSize);
        public void onUploadFinished(boolean bSuccess, String strResult);
    }
}
